package com.sunday.scoremanager.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.adapter.CommonAdapter;
import com.sunday.common.widgets.adapter.ViewHolder;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.common.widgets.swipe.Closeable;
import com.sunday.common.widgets.swipe.OnSwipeMenuItemClickListener;
import com.sunday.common.widgets.swipe.SwipeMenu;
import com.sunday.common.widgets.swipe.SwipeMenuCreator;
import com.sunday.common.widgets.swipe.SwipeMenuItem;
import com.sunday.common.widgets.swipe.SwipeMenuRecyclerView;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.adapter.ProductAdapter;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.base.BaseLazyFragment;
import com.sunday.scoremanager.entity.FanEntity;
import com.sunday.scoremanager.entity.Fans;
import com.sunday.scoremanager.entity.Product;
import com.sunday.scoremanager.http.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/11/1.
 */

public class ProductListFragment extends BaseLazyFragment {
    @Bind(R.id.recycler_view)
    SwipeMenuRecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;


    private long memberId;
    private int pageNo = 1, lastVisibleItem;

    private List<Product> dataSet = new ArrayList<>();
    private ProductAdapter adapter;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;
    private int sort;


    public static ProductListFragment newInstance(int sort) {
        ProductListFragment fragment = new ProductListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("sort", sort);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            sort = getArguments().getInt("sort");
        }
    }

    public int getSort() {
        return sort;
    }

    public void setSort(int sort) {
        this.sort = sort;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_swipe_recycler_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        initRefreshLayout();
        isPrepared = false;
        memberId = BaseApp.getInstance().getMember().getSellerId();
        getData();
    }


    private void initRefreshLayout() {
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new ProductAdapter(mContext, dataSet);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());

        //右滑菜单
        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        recyclerView.setSwipeMenuItemClickListener(menuItemClickListener);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });


        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        emptyLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNo = 1;
                getData();
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNo = 1;
                getData();
            }
        });

        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* Product product= (Product) v.getTag();
                intent=new Intent(mContext,AddProductActivity.class);
                intent.putExtra("product",product);
                startActivity(intent);*/
            }
        });
    }


    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.d60);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            SwipeMenuItem editItem = new SwipeMenuItem(mContext).setBackgroundDrawable(R.color.main_color)
                    .setText(sort == 1 ? "下架" : "上架")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(editItem);

            SwipeMenuItem deleItem = new SwipeMenuItem(mContext).setBackgroundDrawable(R.color.material_red)
                    .setText("删除")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleItem);

        }
    };

    /**
     * 菜单点击监听。
     */
    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        @Override
        public void onItemClick(Closeable closeable, final int adapterPosition, int menuPosition, @SwipeMenuRecyclerView.DirectionMode int direction) {
            switch (direction) {
                case SwipeMenuRecyclerView.LEFT_DIRECTION:
                    break;
                case SwipeMenuRecyclerView.RIGHT_DIRECTION:
                    closeable.smoothCloseMenu();//关闭被点击的菜单
                    if (menuPosition == 0) {
                        //上下架产品
                        upAndDownProduct(dataSet.get(adapterPosition).getId());

                    } else {
                        AlertDialog dialog = new AlertDialog.Builder(mContext).setTitle("温馨提示")
                                .setMessage("确认删除吗")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        deleteProduct(dataSet.get(adapterPosition).getId());
                                        dialog.dismiss();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).show();
                    }

                    break;
            }
        }
    };

    private void upAndDownProduct(long proId) {
        Call<ResultDO> call = ApiClient.getApiAdapter().updateProductStatus(proId, sort == 1 ? 2 : 1);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    pageNo = 1;
                    getData();
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });
    }

    private void deleteProduct(long prdId) {
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().updateProductStatus(prdId, 3);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    pageNo = 1;
                    getData();
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
            }
        });
    }


    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<Product>>> call = ApiClient.getApiAdapter().getProductList(memberId, sort, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<Product>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Product>>> call, Response<ResultDO<List<Product>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                refreshLayout.finishRefresh();
                if (response.body().getCode() == 0) {
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult().size() == Constants.PAGE_SIZE) {
                        pageNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Product>>> call, Throwable t) {
                dissMissDialog();
                refreshLayout.finishRefresh();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
